//
//  WBUserAccount.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/19.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit

private let accountFile:NSString = "UserAccount.json"

class WBUserAccount: NSObject {

    var access_token: String?   //访问令牌
    var uid: String? // 用户代号

    //过期日期（秒），开发者是5年，每次登录都是5年
    //使用者是3天过期，会从第一次登录递减
    var expires_in: TimeInterval = 0{
        didSet{

            expiresDate = Date(timeIntervalSinceNow: expires_in) as NSDate
        }
    }

    var expiresDate: NSDate? //过期日期
    var screen_name: String? //用户昵称 
    var avatar_large: String? //用户头像,大图180*180
    
    

    override var description: String{
        return yy_modelDescription()
    }

    override init() {
        super.init()
        //从磁盘加载保存的文件-> 字典
      guard let path = accountFile.cz_appendDocumentDir(),
        let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any] else{
            return
        }

        //MARK: 2.使用字典设置属性值,控制有无获取token信息
        //**** 用户是否登录的关键代码
        yy_modelSet(with: dict ?? [:])
        print("从沙盒加载用户信息\(self)")
        
        //3.判断token是否过期
//        expiresDate = Date(timeIntervalSinceNow: -3600*24) as NSDate
        //如果expiresDate < 现在时间,过期
        if expiresDate?.compare(Date()) != .orderedDescending{
            print("帐户过期")
            //清空token
            access_token = nil
            uid = nil
            //删除帐户文件
          _ = try? FileManager.default.removeItem(atPath: path)
        }
        print("帐户正常\(self)")
    }


    /**
     1. 偏好设置（小)
     2. 沙盒 - 归档、plist、json
     3. 数据库
     4. 钥匙串访问（小、自动加密 - 需要用框架 SSKeychain）
     */
    func saveAccount() {

        //用json存
        //1.模型转字典 
        var Dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        //删除字段 expires_in
        Dict.removeValue(forKey: "expires_in")
        //2.字典序列化
        let data = try? JSONSerialization.data(withJSONObject: Dict, options: [])
        //3.写入磁盘
        guard let filePath = accountFile.cz_appendDocumentDir() else{
            return
        }

        (data! as NSData).write(toFile: filePath, atomically: true)

        print("用户帐户保存成功\(filePath)")


    }


}
